package com.apache.flow.taskHandler;

import org.jbpm.api.Execution;
import org.jbpm.api.ExecutionService;
import org.jbpm.api.cmd.Command;
import org.jbpm.api.cmd.Environment;
import org.jbpm.pvm.internal.model.ExecutionImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.apache.flow.core.manager.FlowAutomaticProcessingManager;

@SuppressWarnings("rawtypes")
public class ProcessInsOP implements Command {
	/** 
	 * <p>@fields serialVersionUID 
	 */

	private static final long serialVersionUID = -1554504257709719322L;
	private Logger logger = LoggerFactory.getLogger(ProcessInsOP.class);
	private String processInsId;
	private String op;

	public ProcessInsOP(String processInsId, String op) {
		this.processInsId = processInsId;
		this.op = op;
	}

	/**
	 * 实例操作方法
	 */
	@Override
	public Object execute(Environment env) throws Exception {
		ExecutionService executionService = env.get(ExecutionService.class);
		Execution exe = executionService.findProcessInstanceById(processInsId);
		String returnInfo = null;
		if (null != exe) {
			ExecutionImpl impl = (ExecutionImpl) exe;
			FlowAutomaticProcessingManager automaticProcessingManager = env.get(FlowAutomaticProcessingManager.class);
			if (TaskTag.OP_SUSPEND.equals(op.trim())) {//挂起实例
				impl.suspend();
				int i = automaticProcessingManager.updateAutomaticProcessingStatus(processInsId, "1");
				logger.info("挂起实例 【" + processInsId + "】成功,处理自处理任务个数为" + i);
			} else if (TaskTag.OP_RESUME.equals(op.trim())) {//恢复实例
				impl.resume();
				int i = automaticProcessingManager.updateAutomaticProcessingStatus(processInsId, "0");
				logger.info("恢复实例 【" + processInsId + "】成功,处理自处理任务个数为" + i);
			} else if (TaskTag.OP_END.equals(op.trim())) {//终止实例
				impl.end();
				int i = automaticProcessingManager.deleteAutomaticProcessingByProcessInsId(processInsId);
				logger.info("终止实例 【" + processInsId + "】成功,处理自处理任务个数为" + i);
			}
			returnInfo = "T";
		} else {
			returnInfo = "该流程实例不存在";
		}
		return returnInfo;
	}

}
